package com.dq.redis.jedispool;

import com.dq.redis.properties.RedisPropertiesConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cf
 */
@Configuration
public class JedisPoolMyConfig {
    private static ReentrantLock lockPool = new ReentrantLock();

    /**
     * 连接池
     */
    private static JedisPool jedisPool;

    @Autowired
    private RedisPropertiesConfig redisPropertiesConfig;

    /**
     * 配置连接池属性
     */
    private void initialPool() {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(Integer.parseInt(redisPropertiesConfig.getMaxActive()));
            config.setMaxWaitMillis(Integer.parseInt(redisPropertiesConfig.getMaxWait()));
            config.setMaxIdle(Integer.parseInt(redisPropertiesConfig.getMaxIdle()));
            config.setMaxIdle(Integer.parseInt(redisPropertiesConfig.getMinIdle()));


            if(StringUtils.isNotBlank(redisPropertiesConfig.getPassword())) {
                jedisPool = new JedisPool(config,
                        redisPropertiesConfig.getHost(), redisPropertiesConfig.getPort(),
                        Integer.parseInt(redisPropertiesConfig.getTimeout()), redisPropertiesConfig.getPassword());
            }else {
                jedisPool = new JedisPool(config,
                        redisPropertiesConfig.getHost(), redisPropertiesConfig.getPort(),
                        Integer.parseInt(redisPropertiesConfig.getTimeout()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加锁, 初始化连接池
     * @return
     */
    public JedisPool getJedisPool() {
        //多线程时，jedisPool用锁
        lockPool.lock();
        try {
            if (jedisPool == null) {
                initialPool();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lockPool.unlock();
        }
        return jedisPool;
    }

}